﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using K3Cloud.WebApi.Core.IoC.Http;
using K3Ioc = K3Cloud.WebApi.Core.IoC.K3IOCServiceCollectionExtensions;

namespace K3Cloud.WebApi.Core.IoC.K3Client;

/// <summary>
/// K3CloudApiSdk 提供SDK级别的入口，便于初始化和全局配置K3Cloud环境。
/// 支持通过配置文件或委托方式初始化。
/// </summary>
public sealed class K3CloudApiSdk
{
    /// <summary>
    /// 私有构造，禁止外部直接实例化。
    /// </summary>
    private K3CloudApiSdk() { }

    /// <summary>
    /// 创建K3CloudApiSdk实例。
    /// 支持通过配置文件或委托方式初始化全局K3Cloud配置。
    /// </summary>
    /// <param name="setupAction">可选，K3Config配置委托</param>
    /// <returns>K3CloudApiSdk实例</returns>
    public static K3CloudApiSdk Builder(Action<K3Config>? setupAction = default)
    {
        if (setupAction == null && K3Ioc.Configs == null)
        {
            var builder = new ConfigurationBuilder()
                .AddInMemoryCollection()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();
            IConfigurationSection section = builder.GetSection("K3CLOUDCONFIG");
            if (section == null) { throw new ArgumentNullException(nameof(section)); }
            var k3Config = builder.GetValue<K3Config>("K3CLOUDCONFIG") ?? builder.GetSection("K3CLOUDCONFIG").GetChildren().FirstOrDefault()?.Get<K3Config>();
            if (k3Config == null) { throw new ArgumentNullException(nameof(k3Config)); }
            K3Ioc.Configs = k3Config;
        }
        else if (setupAction != null && K3Ioc.Configs == null)
        {
            K3Config config = new();
            setupAction(config);
            K3Ioc.Configs = config;
        }
        if (K3Ioc.Configs == null) { throw new ArgumentNullException(nameof(K3Ioc.Configs)); }
        
        // 使用连接池获取 HttpClient（向后兼容，自动优化）
        if (K3Ioc.HttpClient == null)
        {
            var httpClient = HttpClientFactory.CreateClient(K3Ioc.Configs.Value.ServerHost);
            K3Ioc.HttpClient = new K3HttpService(httpClient, K3Ioc.Configs);
        }
        
        return new K3CloudApiSdk();
    }
    private static async Task<string> PostJsonAsync(string service_url, string sContent = "")
    {
        return await K3Ioc.HttpClient.PostJsonAsync(service_url, sContent);
    }

    /// <summary>
    /// 数据中心
    /// </summary>
    public async Task<string> GetDataCenters()
    {
        return await Execute("Kingdee.BOS.ServiceFacade.ServicesStub.Account.AccountService.GetDataCenterList");
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    public async Task<string> SendMsg(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.SendMsg", data);
    }
    /// <summary>
    /// 保存
    /// </summary>
    public async Task<string> Save(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save", formid, data);
    }

    /// <summary>
    /// 批量保存
    /// </summary>
    public async Task<string> BatchSave(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave", formid, data);
    }

    /// <summary>
    /// 审核
    /// </summary>
    public async Task<string> Audit(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit", formid, data);
    }

    /// <summary>
    /// 删除
    /// </summary>
    public async Task<string> Delete(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete", formid, data);
    }

    /// <summary>
    /// 反审核
    /// </summary>
    public async Task<string> UnAudit(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit", formid, data);
    }

    /// <summary>
    /// 提交
    /// </summary>
    public async Task<string> Submit(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit", formid, data);
    }

    /// <summary>
    /// 查看
    /// </summary>
    public async Task<string> View(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View", formid, data);
    }

    /// <summary>
    /// 单据查询
    /// </summary>
    public async Task<string> ExecuteBillQuery(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery", data);
    }

    public async Task<string> BillQuery(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BillQuery", data);
    }

    /// <summary>
    /// 暂存
    /// </summary>
    public async Task<string> Draft(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Draft", formid, data);
    }

    /// <summary>
    /// 分配
    /// </summary>
    public async Task<string> Allocate(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Allocate", formid, data);
    }

    /// <summary>
    /// 弹性域保存
    /// </summary>
    public async Task<string> FlexSave(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.FlexSave", formid, data);
    }

    /// <summary>
    /// 下推
    /// </summary>
    public async Task<string> Push(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Push", formid, data);
    }

    /// <summary>
    /// 分组保存
    /// </summary>
    public async Task<string> GroupSave(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GroupSave", formid, data);
    }

    /// <summary>
    /// 拆单
    /// </summary>
    public async Task<string> Disassembly(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Disassembly", formid, data);
    }

    /// <summary>
    /// 查询单据接口
    /// </summary>
    public async Task<string> QueryBusinessInfo(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryBusinessInfo", data);
    }

    /// <summary>
    /// 查询分组信息接口
    /// </summary>
    public async Task<string> QueryGroupInfo(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryGroupInfo", data);
    }

    /// <summary>
    /// 工作流审批
    /// </summary>
    public async Task<string> WorkflowAudit(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.WorkflowAudit", data);
    }

    /// <summary>
    /// 分组删除接口
    /// </summary>
    public async Task<string> GroupDelete(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GroupDelete", data);
    }

    /// <summary>
    /// 操作接口
    /// </summary>
    /// <param name="formid">业务对象表单Id</param>
    /// <param name="opNumber">操作编码</param>
    /// <param name="data">数据</param>
    public async Task<string> ExcuteOperation(string formid, string opNumber, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExcuteOperation", JsonConvert.SerializeObject(new { formid, opNumber, data }));
    }

    public async Task<string> ExecuteOperation(string formid, string opNumber, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteOperation", JsonConvert.SerializeObject(new { formid, opNumber, data }));
    }

    /// <summary>
    /// 获取报表数据
    /// </summary>
    public async Task<string> GetSysReportData(string formid, string data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GetSysReportData", formid, data);
    }
    /// <summary>
    /// 自定义接口
    /// </summary>
    public async Task<string> Execute(string servername, object? data = null)
    {
        return await PostJsonAsync($"{K3Ioc.Configs.ServerHost}/{servername}.common.kdsvc", data == null ? "" : JsonConvert.SerializeObject(new { data }));
    }

    public async Task<string> Execute(string servername, string formid, object? data = null)
    {
        return await PostJsonAsync($"{K3Ioc.Configs.ServerHost}/{servername}.common.kdsvc", data == null ? "" : JsonConvert.SerializeObject(new { formid, data }));
    }
    /// <summary>
    /// 自定义接口
    /// </summary>
    public async Task<string> Execute(string servername, string data)
    {
        return await PostJsonAsync($"{K3Ioc.Configs.ServerHost}/{servername}.common.kdsvc", data);
    }
}
